//封装axios
import router from "@/router";
import axios from "axios";

import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";



const router2 = useRouter()

const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000,
});


//请求拦截器
httpInstance.interceptors.request.use(
    (config) => {
        // 在请求发送之前做一些处理
        // 例如添加请求头、修改请求参数等
        const user = localStorage.getItem('user')
        if (user) {
            const token = JSON.parse(user).token
            config.headers['Authorization'] = `Bearer ${token}`;
        }


        return config;
    },
    (error) => {


        // 处理请求错误
        return Promise.reject(error);
    }

);
//响应拦截器
httpInstance.interceptors.response.use(
    (response) => {
        // 处理响应数据
        return response.data;
    },
    (error) => {
        // 处理响应错误
        console.log("error", error.response.status);
        ElMessage({
            message: error.response.data.message,
            type: 'error',
            duration: 2000,
        });

        // 处理 401 未授权错误
        if (error.response?.status === 401) {
            const userStore = useUserStore() // ✅ 在回调中使用 useUserStore
            const router = useRouter()       // ✅ 在回调中使用 useRouter

            userStore.userInfo = {}
            localStorage.removeItem('user')
            router.replace({ path: '/login' })
        }




        // 处理响应错误
        return Promise.reject(error);
    }
);

export default httpInstance;